#!/usr/bin/env python
# coding=utf-8
# version 1.0.0.1

__author__ = 'vavava'

from ConfigParser import ConfigParser
import logging,logging.config
import vavava.util
import os

__version__ = "1.0.0.1"

class Group:
    def __init__(self,group_id,parser):
        self.group_id         =  group_id
        self.auto_start       =  False
        self.db_support       =  False
        self.redoable_supoort =  True
        self.priority_support =  True
        #db
        self.host             =  "localhost"
        self.port             =  3306
        self.db               =  "wr_trace"
        self.user             =  "root"
        self.password         =  "root"
        self.charset          =  "utf-8"
        self.db_pool_min      =  10
        self.db_pool_max      =  20
        self.work_queue_size  =  10

        try:
            self.auto_start        =  parser.getboolean(group_id,"auto_start")
            self.db_support        =  parser.getboolean(group_id,"db_support")
            self.redoable_supoort  =  parser.getboolean(group_id,"redoable_supoort")
            self.priority_support  =  parser.getboolean(group_id,"priority_support")
            self.host              =  parser.get(group_id,"host")
            self.port              =  parser.getint(group_id,"port")
            self.db                =  parser.get(group_id,"db")
            self.user              =  parser.get(group_id,"user")
            self.password          =  parser.get(group_id,"password")
            self.charset           =  parser.get(group_id,"charset")
            self.db_pool_min       =  parser.getint(group_id,"db_pool_min")
            self.db_pool_max       =  parser.getint(group_id,"db_pool_max")
            self.work_queue_size   =  parser.getint(group_id,"work_queue_size")
        except Exception as e:
            raise

class Works:
    def __init__(self,name,parser):
        self.name       = name
        self.auto_start = False
        self.type_name  = ""
        self.type_path  = ""
        self.group_id   = ""
        self.begin_time = None
        self.end_time   = None
        self.period     = 1
        self.args       = None
        self.kargs      = None

        try:
            self.auto_start =  parser.getboolean(name,"auto_start")
            self.type_name  =  parser.get(name,"type_name")
            self.type_path  =  parser.get(name,"type_path")
            self.group_id   =  parser.get(name,"group_id")
            self.begin_time =  parser.get(name,"begin_time")
            self.period     =  parser.getfloat(name,"period")
            self.args       =  self._trans_args(parser.get(name,"args"))
            self.kargs      =  self._trans_kargs(parser.get(name,"kargs"))

            if self.begin_time == "": self.begin_time = None
        except Exception as e:
            print(e)

    def _trans_args(self,arg):
        if arg == "": return []
        args = None
        code = 'def _exec_code(*args): return args \n' \
               'args = _exec_code(%s)\n' % arg
        exec(compile(code,'','exec'))
        return args

    def _trans_kargs(self,karg):
        if karg == "": return {}
        kargs = None
        code = 'def _exec_code(**kargs): return kargs\n'\
               'kargs = _exec_code(%s)\n' % karg
        exec(compile(code,'','exec'))
        return kargs

class TaskServerConfig(object):

    def __init__(self):
        self.fileName = ""
        self.log = None
        self.parser = ConfigParser()
        #version
        self.version         = __version__
        #monitor
        self.listen_ip       =  ""
        self.listen_port     =  4444
        #config
        self.log_config_file =  "./logger.conf"
        self.logger          =  "gripper"
        #runtime
        self.debug_level     =  1
        self.sock_timeout    =  30.0        # s
        self.groups          =  []
        self.works           =  []
        #self._load(fullFileName)

    def load(self,fullFileName=None):
        if fullFileName:
            self.fileName = fullFileName
        if not os.path.exists(fullFileName):
            raise Exception( "file not found %s" % fullFileName )
        self.fileName = os.path.abspath(self.fileName)
        self.parser.read(self.fileName)
        try:
            #version
            version         =  self.parser.get("version","version")
            #monitor
            listen_ip       =  self.parser.get("monitor","listen_ip")
            listen_port     =  self.parser.getint("monitor","listen_port")
            #logger
            log_config_file =  self.parser.get("log","log_config_file")
            logger          =  self.parser.get("log","logger")
            #runtime
            debug_level     =  self.parser.getint("runtime","debug_level")
            sock_timeout    =  self.parser.getfloat("runtime","sock_timeout")
            groups_list     =  self.parser.get("runtime","groups").split(',')
            works_list      =  self.parser.get("runtime","works").split(',')
        except Exception as e:
            print(e)

        if version != __version__ :
            raise Exception("config file not match, need %s, got %s"%
                            (__version__, version))
        #version
        if  version          != "" : self.version         = version
        #monitor
        if  listen_ip        != "" : self.listen_ip       = listen_ip
        if  listen_port            : self.listen_port     = listen_port
        #logger
        if  log_config_file  != "" : self.log_config_file = log_config_file
        if  logger           != "" : self.logger          = logger
        #runtime
        if  debug_level            : self.debug_level     = debug_level
        if  sock_timeout           : self.sock_timeout    = sock_timeout

        for group in groups_list:
            self.groups.append(Group(group,self.parser))

        for work in works_list:
            self.works.append(Works(work,self.parser))

        return self

class TaskServerLog:
    @staticmethod
    def get_logger(task_ser_config):
        vavava.util.assure_path("./log")
        logging.config.fileConfig(task_ser_config.log_config_file)
        return logging.getLogger(task_ser_config.logger)



if __name__ == "__main__":

    config = TaskServerConfig()
    config.load(("task_server.conf"))
    log = TaskServerLog.get_logger(config)
    log.debug("testing ...............")


